package net.mihome.app.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMContactManager;
import com.easemob.chatuidemo.activity.AlertDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.User;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by ZHAO on 2015/1/12 0012.
 */
public class SearchUserAdapter extends BaseAdapter{
    Activity context;
    List<User> users;
    private LayoutInflater listContainer;
    private ProgressDialog progressDialog;
    private Map<String, User> myFriends=null;
    public SearchUserAdapter(Context context,List<User> list){
        this.context= (Activity) context;
        this.users=list;
        listContainer = LayoutInflater.from(context);
        myFriends=AppContext.getInstance().getContactList();
    }
    static class ViewContaiar{
        ImageView avatar;
        TextView name;
        Button addContact;
    }
    @Override
    public int getCount() {
        return users.size();
    }

    @Override
    public Object getItem(int i) {
        return users.get(i);
    }

    @Override
    public long getItemId(int i) {
        return users.get(i).getUid();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        ViewContaiar viewContaiar=null;
        if(view==null){
            viewContaiar=new ViewContaiar();
            view = listContainer.inflate(R.layout.search_user_listitem, viewGroup, false);
            viewContaiar.avatar= (ImageView) view.findViewById(R.id.avatar);
            viewContaiar.name= (TextView) view.findViewById(R.id.name);
            viewContaiar.addContact= (Button) view.findViewById(R.id.indicator);
            view.setTag(viewContaiar);
        }else {
            viewContaiar= (ViewContaiar) view.getTag();
        }

        User user=this.users.get(i);
        if(user!=null){
            ImageLoader.getInstance().displayImage(user.getFace(),viewContaiar.avatar);
            String title=user.getName();
            if(user.getRealName()!=null&&!"".equals(user.getRealName())){
                title=title+"("+user.getRealName()+")";
            }
            viewContaiar.name.setText(title);
            viewContaiar.addContact.setTag(user);
            if(checkIsMyUser(user)){
                viewContaiar.addContact.setText("已添加");
                viewContaiar.addContact.setEnabled(false);
            }else{
                viewContaiar.addContact.setText("添加");
                viewContaiar.addContact.setEnabled(true);
            }
            setOnClickLinster(viewContaiar.addContact);

        }else{
            return view;
        }
        return view;
    }
    public void setOnClickLinster(Button button){
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final User user= (User) view.getTag();
                User curUser=AppContext.getInstance().getLoginInfo();

                String curName= curUser.getName();
                String inputName=user.getName();
                if(curName.equals(inputName)){
                    context.startActivity(new Intent(context, AlertDialog.class).putExtra("msg", "不能添加自己"));
                    return;
                }

                if(AppContext.getInstance().getContactList().containsKey(inputName)){
                    context.startActivity(new Intent(context, AlertDialog.class).putExtra("msg", "此用户已是你的好友"));
                    return;
                }
                showAddMsg(user);

            }
        });
    }
    /**
     * 显示一个对话框，让用户填写好友验证
     * */
    public void showAddMsg(final User user){
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.add_contact_dialog, null);//这里的
        final EditText editText= (EditText) view.findViewById(R.id.add_contact_msg);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
        builder.setTitle("请输入验证信息:");
        builder.setMessage("你想对他(她)说点什么?");
        builder.setView(view);
        builder.setPositiveButton(R.string.text_queding, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(context,"确定",Toast.LENGTH_SHORT).show();
                dialogInterface.dismiss();

                addContact(user,editText.getText().toString());
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }
    /**
     * 启动线程添加好友
     * */
    public void addContact(final User user,final String msg){
                progressDialog = new ProgressDialog(context);
                progressDialog.setMessage("正在发送请求...");
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();

                new Thread(new Runnable() {
                    public void run() {
                        try {
                            //demo写死了个reason，实际应该让用户手动填入
                            EMContactManager.getInstance().addContact(user.getOpenId(), "验证信息:"+msg);
                            context.runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(context, "发送请求成功,等待对方验证", Toast.LENGTH_LONG).show();
                                }
                            });
                        } catch (final Exception e) {
                            context.runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(context, "请求添加好友失败:" + e.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }).start();
    }
    public boolean checkIsMyUser(User user){
        if(myFriends!=null){
            Iterator<String> iterator=myFriends.keySet().iterator();
            while(iterator.hasNext()){
                String key=iterator.next();
                User userTmp=myFriends.get(key);
                if(userTmp==null||userTmp.getOpenId()==null){
                    continue;
                }
                if(userTmp.getOpenId().equals(user.getOpenId())){
                    return true;
                }
            }
        }
        return false;
    }
}
